package com.group.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.base.view.BaseResult;
import com.base.view.GeneralResult;
import com.base.view.ListResult;
import com.group.model.NewsFlash;
import com.group.model.Topic;
import com.group.util.NoteException;

/**
 * 快讯相关
 * 
 * @author zhaolei
 *
 */
@Controller
public class NewsFlashController extends BaseController {

	/**
	 * 添加/修改快讯
	 * 
	 * @param nf
	 * @return
	 */
	@PostMapping("/newsFlash/add")
	@ResponseBody
	public GeneralResult<NewsFlash> addNewsFlash(@RequestBody NewsFlash nf) {

		beanDao.save(nf);

		return new GeneralResult<NewsFlash>().setValue(nf);
	}

	/**
	 * 删除快讯
	 * 
	 * @param newsFlashId
	 * @return
	 */
	@DeleteMapping("/newsFlash/delete")
	@ResponseBody
	public BaseResult deleteNewsFlash(Long newsFlashId) {
		beanDao.quickDelete(NewsFlash.class, "id", newsFlashId);
		return new BaseResult();
	}

	/**
	 * 查询快讯
	 * 
	 * @param key
	 * @param state
	 * @param start
	 * @param limit
	 * @return
	 */
	@GetMapping("/newsFlash/query")
	@ResponseBody
	public ListResult<NewsFlash> queryNewsFlash(String key, Integer state, Integer start, Integer limit) {

		return new ListResult<NewsFlash>().setList(newsDao.queryNewsFlash(key, state, start, limit)).setTotal(newsDao.queryNewsFlashCount(key, state));
	}

	/**
	 * 根据id查询快讯
	 * 
	 * @param newsFlashId
	 * @return
	 */
	@GetMapping("/newsFlash/query/id")
	@ResponseBody
	public GeneralResult<NewsFlash> queryById(Long newsFlashId) {

		return new GeneralResult<NewsFlash>().setValue(beanDao.quickQueryOne(NewsFlash.class, "id", newsFlashId));
	}

	/**
	 * 更新快讯状态
	 * 
	 * @param newsFlashId
	 * @param isImportent
	 * @param state
	 * @return
	 */
	@GetMapping("/newsFlash/state/update")
	@ResponseBody
	public GeneralResult<NewsFlash> updateNewsState(Long newsFlashId, Integer state, Integer isImportent) {
		NewsFlash nf = beanDao.quickQueryOne(NewsFlash.class, "id", newsFlashId);
		if (nf == null) {
			throw new NoteException("快讯 不存在");
		}

		if (state == 1 && nf.getBoardId() != null) {
			// 关联板块发帖
			Topic topic = new Topic();
			topic.setBoardId(nf.getBoardId());
			topic.setNewsFlashId(nf.getId());
			topic.setNewsFlashContent(nf.getContent());
			topic.setNewsFlashTitle(nf.getTitle());
			topic.setIsSelect(nf.getTopicSelect());
			topic.setIsAnalysis(nf.getTopicAnalysis());
			beanDao.save(topic);
		}

		nf.setCreateTime(null);
		nf.setState(state);
		nf.setIsImportent(isImportent);
		beanDao.save(nf);

		return new GeneralResult<NewsFlash>().setValue(nf);
	}

}
